package controllers

import (
	"slotGame/models"
	"strconv"
	"time"

	"slotGame/utils"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/orm"
)

const (
	status_login_init = iota
	status_logined
	status_logout
	status_login_err
)

// LoginController oprations for Login
type LoginController struct {
	beego.Controller
}

// URLMapping ...
func (c *LoginController) URLMapping() {
	c.Mapping("GetOne", c.Login)
	c.Mapping("GetOne", c.LoginOut)

}

// Login ...
// @Title login
// @Description get Login by id   测试id : qkkncuq7vcpcir93ttf65fo7t3
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Login
// @Failure 401 : 请重新登录
// @router /:id [get]
func (c *LoginController) Login() {
	print("----logincontroller login")
	idStr := c.Ctx.Input.Param(":id")

	req := httplib.Get(beego.AppConfig.String("get_user_info") + idStr)
	//	req := httplib.Get("http://localhost/test/a.php")
	// var resp models.Responses
	var resp models.Responses

	if headResp, err := req.Response(); err == nil {
		if headResp.StatusCode == 200 {
			req.ToJSON(&resp)
			if resp.Code == 9999 {
				// c.Ctx.Output.SetStatus(777)

				out := utils.Reponse(401, nil, "请重新登录", "sid无效")

				c.Data["json"] = out

			} else if resp.Code == 0 {
				user_id, _ := strconv.Atoi(resp.Data.Member.Id)
				username := resp.Data.Member.Name
				v, err := models.GetLoginByUserId(user_id)

				logins := models.Login{LoginStatus: 1, UserId: user_id, UserName: username}

				if err != nil {
					logins.CreateTime = time.Now()
					if _, err := models.AddLogin(&logins); err != nil {
						logins.LoginStatus = status_logined
					} else {
						logins.LoginStatus = status_login_err
					}
					out := utils.Reponse(200, &logins, "Success", nil)

					c.Data["json"] = out

				} else {
					print("updateloginbyuserid")
					logins.Id = v.Id
					logins.CreateTime = v.CreateTime
					if err := models.UpdateLoginByUserId(&logins); err != nil {

						v.LoginStatus = status_logined
					} else {
						v.LoginStatus = status_login_err
					}

					out := utils.Reponse(200, v, "Success", nil)
					c.Data["json"] = out

				}
			}
			c.ServeJSON()
		} else {
			beego.SetLogger("file", `{"filename":"log/login.log"}`)
		}

	}
}

// LoginOut
// @Title stopcard
// @Description 0 user win  1 banker win
// @Param userid query string true "67351"
// @Success 200 返回成功
// @Failure 400 请求参数错误或者没有数椐
// @router /loginout [get]
func (c *LoginController) LoginOut() {
	o := orm.NewOrm()

	user_id := c.GetString("userid")
	intUserID, _ := strconv.Atoi(user_id)
	v, err := models.GetLoginByUserId(intUserID)

	if err == nil {
		v.LoginStatus = status_logout
		if _, err = o.Update(v); err == nil {
			out := utils.Reponse(200, nil, "Success", nil)
			c.Data["json"] = out
			c.ServeJSON()
		} else {
			out := utils.Reponse(403, nil, "fail", nil)
			c.Data["json"] = out
			c.ServeJSON()
		}
	}

}
